﻿using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using BadgeManager.Controller;
using BadgeManager.Model;
using BadgeManager.Properties;

namespace BadgeManager
{
    public partial class frmMain : Form
    {
        private bool PrimoPianoForm;

        public frmMain()
        {
            InitializeComponent();
            this.Text += " [" + Application.ProductVersion + "]";
            PrimoPianoForm = Settings.Default.PrimoPiano;
            primoPianoToolStripMenuItem.Checked = PrimoPianoForm;
            this.TopMost = PrimoPianoForm;
            txtInput.LostFocus += new EventHandler(delegate(object sender, EventArgs e)
            {
                txtInput.Focus();
                txtInput.Select();
            });
            //this.LostFocus += new EventHandler(delegate(object ob, EventArgs e)
            //    {
            //        this.Activate();
            //        IsIstance();
            //    });

            ScriviLog("> Avviato");
        }

        [DllImport("user32")]
        static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32")]
        static extern int ShowWindow(IntPtr hWnd, int swCommand);

        [DllImport("user32")]
        static extern bool IsIconic(IntPtr hWnd);

        private static bool IsIstance()
        {
            Process proc = Process.GetCurrentProcess();

            string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
#if DEBUG
            assemblyName = Assembly.GetExecutingAssembly().GetName().Name + ".vshost";
#endif

            //foreach (Process altriProc in Process.GetProcessesByName(assemblyName))
            //{
            IntPtr hWnd = Process.GetCurrentProcess().MainWindowHandle;

            if (IsIconic(hWnd))
                ShowWindow(hWnd, 9); //SW_RESTORE

            SetForegroundWindow(hWnd);

            //}
            return true;
        }

        private void uscitaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ControllaAccesso(string codicetessera)
        {
            if (txtInput.Text.Trim() == "")
                return;

            if (txtInput.Text.Length != 12)
            {
                return;
            }

            ctrlAccessi cAccessi = new ctrlAccessi();
            try
            {
                cAccessi.EseguiAccesso(txtInput.Text);
            }
            catch (TesseraNuovaExeption)
            {
                ScriviLog("Tessera [" + txtInput.Text + "] inesistente - " + (cAccessi.Persona != null ? cAccessi.Persona.ToString() : ""));
            }
            catch (TesseraAttivaInUnCorsoException ex) 
            {
                ScriviLog("Porta Aperta - " + (cAccessi.Persona != null ? cAccessi.Persona.ToString() : ""));
            }
            catch (RiciclareCorsoFinitoException ex) 
            {
                ScriviLog("Tessera [" + txtInput.Text + "] non associata ad un attivita valida - " + (cAccessi.Persona != null ? cAccessi.Persona.ToString() : ""));
            }
            catch (TesseraNonAbilitata)
            {
                ScriviLog("Tessera [" + txtInput.Text + "] non abilitata - " + (cAccessi.Persona != null ? cAccessi.Persona.ToString() : ""));
            }
            catch (TesseraEsistenteMaNonAssociata)
            {
                ScriviLog("Tessera [" + txtInput.Text + "] non associata a persona - " + (cAccessi.Persona != null ? cAccessi.Persona.ToString() : ""));
            }
        }

        private void ScriviLog(string testo)
        {
            txtLog.AppendText(testo + " [" + DateTime.Now + "] \r\n");
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult scelta = MessageBox.Show("Vuoi terminare l'esecuzione del server?"
                , "Termina esecuzione", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (scelta == System.Windows.Forms.DialogResult.Yes)
                e.Cancel = false;
            else
                e.Cancel = true;
        }

        private void txtInput_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                ControllaAccesso(txtInput.Text.Trim());
                txtInput.Text = "";
            }
        }

        private void infoSuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmInfos frm = new frmInfos();
            frm.TopMost = PrimoPianoForm;
            frm.ShowDialog();
        }

        private void primoPianoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Settings.Default.PrimoPiano = primoPianoToolStripMenuItem.Checked;
            PrimoPianoForm = primoPianoToolStripMenuItem.Checked;
            Settings.Default.Save();
        }

        private void salvaConNomeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (txtLog.Text.Trim().Length == 0) { return; }
            dialog.FileName = "";
            dialog.Filter = "File di testo (.txt)|*.txt";
            dialog.ShowDialog();

            if (dialog.FileName != "")
            {
                SalvaLog(dialog.FileName);
            }
        }

        private void SalvaLog(string percorso)
        {
            StreamWriter sw;
            sw = File.CreateText(percorso);
            sw.WriteLine(txtLog.Text);
            sw.Flush();
            sw.Close();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            IsIstance();
        }

        private void disattivaControlloFOCUSToolStripMenuItem_Click(object sender, EventArgs e)
        {
            timer1.Enabled = !disattivaControlloFOCUSToolStripMenuItem.Checked;
        }
    }
}